package com.autowite.autowite.utils;

import com.alibaba.excel.util.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class FormFiller {

    private final WebDriver driver;

    public FormFiller() {
        // 设置 ChromeDriver 的路径
        System.setProperty("webdriver.chrome.driver", "C:\\kaifaruanjian\\chromedriver-win64\\chromedriver.exe");
        // 初始化 WebDriver
        driver = new ChromeDriver();
    }

    public void openPage(WebDriver webDriver,String url) {
        webDriver.get(url);
    }


    // 输入框
    private void fillInputField(String fieldId, String value) {
        WebElement field = driver.findElement(By.id(fieldId));
        field.sendKeys(value);
    }

    /**
     * 下拉框根据id选中
     * @param dropdownId  页面中元素id
     * @param value  选中值
     */
    private void selectDropdown(String dropdownId, String value) {
        // 等待加载时间 最大十秒
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        WebElement dropdown = driver.findElement(By.id(dropdownId));
        wait.until(ExpectedConditions.visibilityOf(dropdown));
        // 先点击
        dropdown.click();
        // 后选中
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("select#" + dropdownId + " option[value='" + value + "']")));
        new Select(dropdown).selectByValue(value);
    }

    /**
     * 提交按钮 默认值submit
     * @param id
     */
    private void submitForm(String submitId) {
        String submitId = StringUtils.isEmpty(submitId) ? "submit" : submitId;
        WebElement submitButton = driver.findElement(By.id(submitId));
        submitButton.click();
    }

    public void close() {
        driver.quit();
    }

}
